package org.opens.mybatisplus.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.opens.mybatisplus.pojo.dto.MyBatisPerson;
import org.opens.mybatisplus.service.MybatisPersonService;
import org.opens.util.PageUtil;
import org.opens.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/api")
// 使该接口可以跨域请求
@CrossOrigin(origins = "*", maxAge = 3600, allowCredentials = "true")
public class MybatisPersonController {

    @Autowired
    private MybatisPersonService mybatisPersonService;

    @PostMapping(value = "/person")
    public R insertAndReturnId(
            @RequestBody MyBatisPerson myBatisPerson
    ) {
        Integer id = mybatisPersonService.insertAndReturnId(myBatisPerson);
        R success = R.success("插入成功");
        success.put("id", id);
        return success;
    }

    @DeleteMapping(value = "/person/{id}")
    public R deleteById(
            @PathVariable(value = "id") Integer id
    ) {
        R result = R.success("删除成功");
        try {
            mybatisPersonService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "删除失败");
        }
        return result;
    }

    @PatchMapping(value = "/person")
    public R update(
            @RequestBody MyBatisPerson person
    ) {
        R result = R.success("更新成功");
        try {
            mybatisPersonService.update(person);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "更新失败");
        }
        return result;
    }

    @GetMapping(value = "/person/{id}")
    public R getOne(
            @PathVariable(value = "id") Integer id
    ) {
        R result = R.success("获取成功");
        try {
            MyBatisPerson person = mybatisPersonService.findById(id);
            result.put("data", person);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", String.format("id:%d对应的数据不存在", id));
        }
        return result;
    }

    @GetMapping(value = "/person/page")
    public PageUtil queryPage(
            @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @RequestParam(value = "pageSize", required = false, defaultValue = "3") Integer pageSize,
            MyBatisPerson person
    ) {
        IPage<MyBatisPerson> page = mybatisPersonService.pageOfCondition(pageNumber, pageSize, person);
        return new PageUtil(new Long(page.getTotal()).intValue(), page.getRecords());
    }

}
